package leecode

import "sort"

func smallestNumber(num int64) int64 {
	if num == 0 {
		return 0
	}
	arr := getNums2165(num)
	var result int64
	if num < 0 {
		for i := len(arr) - 1; i >= 0; i-- {
			result = result*10 + arr[i]
		}
		return -result
	}
	//统计arr中前导0的个数
	zeroCount := 0
	for _, n := range arr {
		if n == 0 {
			zeroCount++
		} else {
			break
		}
	}

	result = arr[zeroCount]
	temp := zeroCount
	for zeroCount > 0 {
		result = result*10 + 0
		zeroCount--
	}
	for i := temp + 1; i < len(arr); i++ {
		result = result*10 + arr[i]
	}
	return result
}

func getNums2165(num int64) []int64 {
	if num < 0 {
		num = -num
	}
	var nums []int64
	for num > 0 {
		nums = append(nums, num%10)
		num = num / 10
	}
	sort.Slice(nums, func(i, j int) bool {
		return nums[i] < nums[j]
	})
	return nums
}
